<?php

namespace app\admin\controller;

use think\Validate;
use think\Db;
use app\models\{Banner, Cate, Config, Annous, Agent as Agents, Message, Subcate, Product, Autoorder, Region, Payment};

class System extends Base
{


    public function recharge()
    {
        if ($this->request->isAjax()) {
            $model = new Payment();
            $page = input('page/d') ?? 1;
            $post = input();
            $limit = input('limit/d') ?? 10;
            $where = array();
            $where[] = ['status','=',2];
            if (!empty($post['paytype'])) {
                $where[] = ['paytype', '=',$post['paytype']];
            }
            if (!empty($post['type'])) {
                $where[] = ['type', '=',$post['type']];
            }
            if (!empty($post['refund'])) {
                $where[] = ['refund', '=',$post['refund']];
            }
            if (!empty($post['title'])) {
                $where[] = ['user_id|paymentid|out_refund_no|ordersn', '=',$post['title']];
            }
            $count = $model->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $model->where($where)->order(["id" => 'desc'])->limit($limit)->page($page)->select();
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            return view(null, []);
        }
    } 


    public function subcate()
    {
        if ($this->request->isAjax()) {
            $model = new Subcate();
            $post = input();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $where = array();
            $where[] = ['agentid', '=', 0];
            if (!empty($post['title'])) {
                $where[] = ['name', 'like', '%' . $post['title'] . '%'];
            }
            if (!empty($post['cate'])) {
                $where[] = ['cate', '=', $post['cate']];
            }
            if (!empty($post['isshow'])) {
                $where[] = ['isshow', '=', $post['isshow']];
            }
            $count = $model->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $model->where($where)->order(["sort" => "desc", "id" => 'desc'])->limit($limit)->page($page)->select();
            foreach ($list as $lists) {
                $lists['cate_name'] = (new Cate())->where(['id' => $lists['cate']])->value('name') ?? '无';
            }
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            return view(null, [
                'cate' => (new Cate())->field('id,name,isshow')->order(['sort' => 'desc'])->select()
            ]);
        }
    }


    public function product()
    {
        if ($this->request->isAjax()) {
            $model = new Product();
            $post = input();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $where = array();
            $where[] = ['isdel', '=', 1];
            $where[] = ['agentid', '=', 0];
            if (!empty($post['title'])) {
                $where[] = ['title', 'like', '%' . $post['title'] . '%'];
            }
            if (!empty($post['cate'])) {
                $where[] = ['cate', '=', $post['cate']];
            }
            if (!empty($post['subcate'])) {
                $where[] = ['subcate', '=', $post['subcate']];
            }
            if (!empty($post['isshow'])) {
                $where[] = ['isshow', '=', $post['isshow']];
            }
            if (!empty($post['ishot'])) {
                $where[] = ['ishot', '=', $post['ishot']];
            }
            $count = $model->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $model->where($where)->order(["sort" => "desc", "id" => 'desc'])->limit($limit)->page($page)->select();
            foreach ($list as $lists) {
                $lists['cate_name'] = (new Cate())->where(['id' => $lists['cate']])->value('name') ?? '无';
                $lists['subcate_name'] = (new Subcate())->where(['id' => $lists['subcate']])->value('name') ?? '无';
            }
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            return view(null, [
                'cate' => (new Cate())->field('id,name,isshow')->order(['sort' => 'desc'])->select(),
                'subcate' => (new Subcate())->field('id,name,isshow')->order(['sort' => 'desc'])->select()
            ]);
        }
    }

    public function message()
    {
        if ($this->request->isAjax()) {
            $model = new Message();
            $post = input();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $where = array();
            if (!empty($post['type'])) {
                $where[] = ['type', '=', $post['type']];
            }
            if (!empty($post['status'])) {
                $where[] = ['status', '=', $post['status']];
            }
            if (!empty($post['title'])) {
                $where[] = ['mobile', 'like', '%' . $post['title'] . '%'];
            }
            $count = $model->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $model->where($where)->order(["id" => 'desc'])->limit($limit)->page($page)->select();
            foreach ($list as $lists) {
                $lists['images'] = json_decode($lists['images'], true) ?? [];
            }
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            return view(null, []);
        }
    }

    public function replymessage()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require',
                'reply' => 'require'
            ], [
                'id.require' => '回复ID不能为空',
                'reply.require' => '回复内容不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['status' => 1, 'msg' =>  $validate->getError()]);
            }
            $data['status'] = 2;
            $model = new Message();
            $res = $model->allowfield(true)->save($data, ['id' => $data['id']]);
            if ($res) {
                return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
            }
            return json(['code' => 1, 'data' => [], 'msg' => '操作失败，请重试']);
        }
    }

    public function cate()
    {
        if ($this->request->isAjax()) {
            $model = new Cate();
            $post = input();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $where = array();
            if (!empty($post['title'])) {
                $where[] = ['name', 'like', '%' . $post['title'] . '%'];
            }
            $count = $model->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $model->where($where)->order(["sort" => "desc", "id" => 'desc'])->limit($limit)->page($page)->select();
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            return view(null, []);
        }
    }


    public function cate_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'name' => 'require',
                'images' => 'require'
            ], [
                'name.require' => '分类名称不能为空',
                'images.require' => '图片路径不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['status' => 1, 'msg' =>  $validate->getError()]);
            }
            $model = new Cate();
            if (!empty($data['id'])) {
                $res = $model->allowfield(true)->save($data, ['id' => $data['id']]);
            } else {
                $res = $model->allowfield(true)->save($data);
            }
            if ($res) {
                return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
            }
            return json(['code' => 1, 'data' => [], 'msg' => '操作失败，请重试']);
        } else {
            $model = new Cate();
            $id = $this->request->get('id/d', 0);
            $row = $model->where('id', $id)->find();
            return view('', [
                'row' => $row,
            ]);
        }
    }


    public function cate_status()
    {
        $id = input('id');
        $field = input('field/s', '');
        if (!empty($id) && !empty($field)) {
            $model = new Cate();
            $cate = $model->where(['id' => $id])->find();
            if (empty($cate)) {
                return json(['code' => 1, 'data' => [], 'msg' => '数据不存在,请刷新页面重试']);
            }
            switch ($field) {
                case 'isshow':
                    $status = $cate['isshow'] == 1 ? 2 : 1;
                    break;
                default:
                    return json(['code' => 1, 'data' => [], 'msg' => '数据类型错误,请刷新页面重试']);
                    break;
            }
            Db::startTrans();
            try {
                $model->where(['id' => $id])->update([$field => $status]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1, 'data' => [], 'msg' => $e->getMessage()]);
            }
            return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
        }
        return json(['code' => 1, 'data' => [], 'msg' => '操作失败']);
    }

    public function cate_del()
    {
        $id = input('id');
        if (!empty($id)) {
            $model = new Cate();
            Db::startTrans();
            try {
                $model->where(['id' => $id])->delete();
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1, 'data' => [], 'msg' => $e->getMessage()]);
            }
            return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
        }
        return json(['code' => 1, 'data' => [], 'msg' => '操作失败']);
    }

    public function banner()
    {
        if ($this->request->isAjax()) {
            $model = new Banner();
            $post = input();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $where = array();
            if (!empty($post['title'])) {
                $where[] = ['title', 'like', '%' . $post['title'] . '%'];
            }
            if (!empty($post['types'])) {
                $where[] = ['types', '=', $post['types']];
            }
            if (!empty($post['agentid'])) {
                if ($post['agentid'] == -1) {
                    $post['agentid'] = 0;
                }
                $where[] = ['agentid', '=', $post['agentid']];
            }
            $count = $model->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $model->where($where)->order("id desc")->limit($limit)->page($page)->select();
            foreach ($list as $row) {
                $row['agent_name'] = (new Agents())->where(['id' => $row['agentid']])->value('nickname') ?? '系统';
            }
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            return view(null, [
                'agent' => (new Agents())->field('id,nickname,accounts')->where(['status' => [1, 2]])->select()
            ]);
        }
    }

    public function banner_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'title' => 'require',
                'agentid' => 'require',
                'types' => 'require|in:1,2,3',
                'url' => 'require'
            ], [
                'title.require' => '轮播图备注信息不能为空',
                'agentid.require' => '类型选择不能为空',
                'types.require' => '类别选择不能为空',
                'types.in' => '类别不正确',
                'url.require' => '图片路径不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['status' => 1, 'msg' =>  $validate->getError()]);
            }
            $model = new Banner();
            //查找店铺名称、账号是否已经被使用
            if (!empty($data['id'])) {
                $res = $model->allowfield(true)->save($data, ['id' => $data['id']]);
            } else {
                $res = $model->allowfield(true)->save($data);
            }
            if ($res) {
                return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
            }
            return json(['code' => 1, 'data' => [], 'msg' => '操作失败，请重试']);
        } else {
            $model = new Banner();
            $id = $this->request->get('id/d', 0);
            $row = $model->where('id', $id)->find();
            return view('', [
                'row' => $row,
                'agent' => (new Agents())->field('id,nickname,accounts')->where(['status' => [1, 2]])->select()
            ]);
        }
    }

    public function banner_del()
    {
        $id = input('id');
        if (!empty($id)) {
            $model = new Banner();
            Db::startTrans();
            try {
                $model->where(['id' => $id])->delete();
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1, 'data' => [], 'msg' => $e->getMessage()]);
            }
            return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
        }
        return json(['code' => 1, 'data' => [], 'msg' => '操作失败']);
    }


    public function annous()
    {
        if ($this->request->isAjax()) {
            $model = new Annous();
            $post = input();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $where = array();
            if (!empty($post['title'])) {
                $where[] = ['title', 'like', '%' . $post['title'] . '%'];
            }
            if (!empty($post['types'])) {
                $where[] = ['types', '=', $post['types']];
            }
            if (!empty($post['agentid'])) {
                if ($post['agentid'] == -1) {
                    $post['agentid'] = 0;
                }
                $where[] = ['agentid', '=', $post['agentid']];
            }
            $count = $model->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $model->where($where)->order("id desc")->limit($limit)->page($page)->select();
            foreach ($list as $row) {
                $row['agent_name'] = (new Agents())->where(['id' => $row['agentid']])->value('nickname') ?? '系统';
            }
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            return view(null, [
                'agent' => (new Agents())->field('id,nickname,accounts')->where(['status' => [1, 2]])->select()
            ]);
        }
    }

    public function annous_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'title' => 'require',
                'agentid' => 'require',
                'types' => 'require|in:1,2',
                'content' => 'require'
            ], [
                'title.require' => '轮播图备注信息不能为空',
                'agentid.require' => '类型选择不能为空',
                'types.require' => '类别选择不能为空',
                'types.in' => '类别不正确',
                'content.require' => '内容不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['status' => 1, 'msg' =>  $validate->getError()]);
            }
            $model = new Annous();
            //查找店铺名称、账号是否已经被使用
            if (!empty($data['id'])) {
                $res = $model->allowfield(true)->save($data, ['id' => $data['id']]);
            } else {
                $res = $model->allowfield(true)->save($data);
            }
            if ($res) {
                return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
            }
            return json(['code' => 1, 'data' => [], 'msg' => '操作失败，请重试']);
        } else {
            $model = new Annous();
            $id = $this->request->get('id/d', 0);
            $row = $model->where('id', $id)->find();
            return view('', [
                'row' => $row,
                'agent' => (new Agents())->field('id,nickname,accounts')->where(['status' => [1, 2]])->select()
            ]);
        }
    }

    public function annous_del()
    {
        $id = input('id');
        if (!empty($id)) {
            $model = new Annous();
            Db::startTrans();
            try {
                $model->where(['id' => $id])->delete();
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1, 'data' => [], 'msg' => $e->getMessage()]);
            }
            return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
        }
        return json(['code' => 1, 'data' => [], 'msg' => '操作失败']);
    }

    public function config()
    {
        if ($this->request->isAjax()) {
            $model = new Config();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $where = array();
            $count = $model->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $model->where($where)->limit($limit)->page($page)->select();
            foreach ($list as $lists) {
                if ($lists['name'] == 'hdsm'  || $lists['name'] == 'sfys' || $lists['name'] == 'myus' || $lists['name'] == 'sfxy' || $lists['name'] == 'yqcoun' || $lists['name'] == 'ydgzh') {
                    $lists['value'] = '请编辑内查看内容';
                }
                if ($lists['name'] == 'withfee') {
                    $lists['value'] = $lists['value'] . '%';
                }
                if ($lists['name'] == 'nyqcoun') {
                    $lists['value'] = $lists['value'] . '元';
                }
            }
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            return view(null, []);
        }
    }


    public function config_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'name' => 'require',
                'value' => 'require'
            ], [
                'name.require' => '名称不能为空',
                'value.require' => '路径不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'msg' =>  $validate->getError()]);
            }
            if ($data['name'] == 'withfee') {
                $data['value'] = (float)$data['value'];
                $data['value'] = floor($data['value'] * 100) / 100;
                if ($data['value'] < 0 || $data['value'] > 100) {
                    return json(['code' => 1, 'msg' =>  '参数值错误，请填写范围0-100且最多保留2位小数']);
                }
            }
            if ($data['name'] == 'nyqcoun') {
                $data['value'] = (float)$data['value'];
                if ($data['value'] < 0 || $data['value'] > 100) {
                    return json(['code' => 1, 'msg' =>  '参数值错误，参数值必须大于0']);
                }
            }
            if ($data['name'] == 'yqcoun') {
                $data['value'] = json_encode($data['value'], true);
                if (is_null(json_decode($data['value']))) {
                    return json(['code' => 1, 'msg' =>  '请填写正确json数据']);
                }
            }
            $res = (new Config())->allowfield(true)->save($data, ['name' => $data['name']]);
            if ($res) {
                return json(['code' => 200, 'msg' => '编辑成功']);
            }
            return json(['code' => 1, 'msg' => '编辑失败']);
        } else {
            $name = $this->request->get('name/s', '');
            $row = (new Config())->where('name', $name)->find();
            if (!empty($row) && ($row['name'] == 'yqcoun')) {
                $row['value'] = json_decode($row['value'], true);
                if (!is_array($row['value'])) {
                    $row['value'] = [];
                }
            }
            return view('', [
                'row' => $row
            ]);
        }
    }
}
